package com.atguigu.demojuc.chap06;

import java.util.concurrent.*;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

class Ticket {
    private int number = 50;
    private final ReentrantLock lock = new ReentrantLock(true);
    private final Condition condition = lock.newCondition();
    public void save() {
        lock.lock();
        try {
            while (number > 0) {
                System.out.println(Thread.currentThread().getName() + " 正在卖第 " + (50 - number + 1) + " 张票");
                Thread.sleep(100);
                number--;
                condition.signalAll();
                if (number > 0) {
                    condition.await();
                }
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
}

public class ThreadPoolTest {
    public static void main(String[] args)  {
        Ticket ticket = new Ticket();
        CountDownLatch countDownLatch = new CountDownLatch(3);
        ExecutorService threadPool = new ThreadPoolExecutor(3, 5, 2, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(5),
                new ThreadPoolExecutor.AbortPolicy());
        for (int i = 0; i < 3; i++) {
            threadPool.execute(() -> {
                ticket.save();
                countDownLatch.countDown();
            });
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("票已卖完");
        threadPool.shutdown();
    }
}
